/*
 * @Description: 这个文件和业务没有关系
 * @Author bianpengfei
 * @create 2021/12/27 20:58
 * */
import { make } from 'vuex-pathify'
import defaultSetting from '@/setting'
import { treeToList } from '@bianpengfei/utils'

const { app } = JSON.parse(localStorage.getItem(defaultSetting.localstorageEntry.systemInfo)) || {}

const state = {
  loading: false, // 菊花loading
  iconfont: 'iconfont-ps', // 字体图标
  headerShow: defaultSetting.headerShow, // header是否展示
  menuShow: defaultSetting.menuShow, // 菜单是否展示
  navShow: defaultSetting.navShow, // 导航栏是否展示
  breadcrumbShow: app?.breadcrumbShow || defaultSetting.breadcrumbShow, // 面包屑是否展示
  settingVisible: false, // 设置展示
  menuIsCollapse: app?.menuIsCollapse || false, // 菜单是否收缩
  breadcrumb: [], // 面包屑
  navArr: app?.navArr || [], // 导航
  menus: app?.menus || [], // 菜单树状
  menusList: [], // 菜单列表
  menuDefaultActive: {},
  navDraggable: app?.navDraggable != null ? app?.navDraggable : defaultSetting.navDraggable, // 是否允许开启 导航tag 鼠标拖动
  weekMode: app?.weekMode != null ? app?.weekMode : defaultSetting.weekMode, // 色弱模式
  theme: app?.theme || defaultSetting.theme,
  transitionEnable: app?.transitionEnable != null ? app?.transitionEnable : defaultSetting.transitionEnable, // 是否开启页面过度动画
  transitionName: app?.transitionName || defaultSetting.transitionName, // 页面过度动画
  primaryColor: app?.primaryColor || defaultSetting.primaryColor, // 主要颜色
  menusDefaultOpeneds: app?.menusDefaultOpeneds || [], // 默认打开的菜单
  layout: app?.layout || defaultSetting.layout, // vertical 垂直布局   horizontal 水平布局 horizontal-vertical 水平+垂直布局
  isExternal: false, // 是否是外部 默认是false
  routingStack: [], // 路由堆栈
  routePosition: {}, // 路由滚动条位置 例子{'/index/home', {x: 10, y: 100}}
  routeDirection: '' // 判断路由是 前进还是后退 前进 forward  后退：backward
}
const mutations = {
  ...make.mutations(state)
}

const actions = {
  ...make.actions(state),

  /**
   * 添加路由堆栈
   * @param state
   * @param commit
   * @param data
   */
  pushRoutingStack({ state, commit }, data) {
    const { routingStack, routePosition } = state
    const idx = routingStack.findIndex((v) => v.fullPath == data.fullPath)
    let routeStackNew = []
    if (idx >= 0) {
      routeStackNew = routingStack.slice(0, idx + 1)
    } else {
      routeStackNew = routingStack.concat(data)
    }
    // const prefixArr = routeStackNew.map(v => v.fullPath)
    const routePositionNew = Object.keys(routePosition).reduce((p, c) => {
      // if (prefixArr.includes(c)) {
      //   p[c] = routePosition[c]
      // }
      p[c] = routePosition[c]
      return p
    }, {})
    commit('routingStack', routeStackNew)
    commit('routePosition', routePositionNew)
  },

  /**
   * 添加nav
   * @param state
   * @param commit
   * @param data
   */
  addNavArrItem({ state, commit }, data) {
    const { navArr } = state
    const idx = navArr.findIndex((v) => v.fullPath == data.fullPath)
    if (idx >= 0) {
      // 存在
      let title = data?.meta?.title
      navArr.splice(idx, 1, {
        ...data,
        title: navArr[idx]?.title?.includes(title) ? navArr[idx]?.title : title
      })
      commit('navArr', [...navArr])
    } else {
      // 不存在
      commit('navArr', [
        ...navArr,
        {
          ...data,
          title: data?.meta?.title
        }
      ])
    }
  },

  /* 移除nav*/
  removeNavItem({ state, commit }, data) {
    const { navArr, routePosition } = state
    const curIdx = navArr.findIndex((v) => v.fullPath == data.fullPath)
    if (curIdx != -1) {
      const map = new Map()
        .set('left', () => {
          const navArrFilter = navArr.filter((v, i) => i >= curIdx)
          let routePositionNew = JSON.parse(JSON.stringify(routePosition))
          navArrFilter.forEach((v) => {
            if (routePositionNew[v.fullPath]) {
              delete routePositionNew[v.fullPath]
            }
          })
          commit('navArr', navArrFilter)
          commit('routePosition', routePositionNew)
        })
        .set('right', () => {
          const navArrFilter = navArr.filter((v, i) => i <= curIdx)
          let routePositionNew = JSON.parse(JSON.stringify(routePosition))
          navArrFilter.forEach((v) => {
            if (routePositionNew[v.fullPath]) {
              delete routePositionNew[v.fullPath]
            }
          })
          commit('navArr', navArrFilter)
          commit('routePosition', routePositionNew)
        })
        .set('others', () => {
          const navArrFilter = navArr.filter((v, i) => i == curIdx)
          let routePositionNew = JSON.parse(JSON.stringify(routePosition))
          navArrFilter.forEach((v) => {
            if (routePositionNew[v.fullPath]) {
              delete routePositionNew[v.fullPath]
            }
          })
          commit('navArr', navArrFilter)
          commit('routePosition', routePositionNew)
        })
        .set('default', () => {
          const navArrFilter = navArr.filter((v, i) => i != curIdx)
          let routePositionNew = JSON.parse(JSON.stringify(routePosition))
          if (routePositionNew[data.fullPath]) {
            delete routePositionNew[data.fullPath]
          }
          commit('navArr', navArrFilter)
          commit('routePosition', routePositionNew)
        })
      map.get(data.flag)()
    }
  },

  /**
   * 添加 当前打开的 sub-menu 的 index 的数组
   * @param state
   * @param commit
   * @param data
   */
  addMenusDefaultOpeneds({ state, commit }, data) {
    const { menusDefaultOpeneds } = state
    commit('menusDefaultOpeneds', [...new Set([...menusDefaultOpeneds, data])])
  },

  /**
   * 移除 当前打开的 sub-menu 的 index 的数组
   * @param state
   * @param commit
   * @param data
   */
  removeMenusDefaultOpeneds({ state, commit }, data) {
    const { menusDefaultOpeneds } = state
    commit(
      'menusDefaultOpeneds',
      menusDefaultOpeneds.filter((v) => v != data)
    )
  },

  /**
   * 设置动态路由
   * @param commit
   * @param {Array} data
   * @returns {*}
   */
  setDynamicRoutes({ commit }, data = []) {
    const menusList = treeToList({
      tree: JSON.parse(JSON.stringify(data)),
      props: {
        id: 'id',
        parentId: 'parentId',
        children: 'children'
      },
      retainChild: true
    })
    commit('menus', data)
    commit('menusList', menusList)
  },

  /**
   * 设置tabs 中某一个item里面数据内容
   * @param state
   * @param commit
   * @param data
   */
  setTabsNavItem({ state, commit }, data = { name: '', path: '', fullPath: '', meta: {}, params: {}, query: {} }) {
    const { navArr } = state
    if (data.fullPath) {
      const index = navArr.findIndex((item) => item.fullPath == data.fullPath)
      if (index >= 0) {
        console.log('setTabsNavItem', data, navArr[index])
        navArr.splice(index, 1, { ...navArr[index], ...data })
        commit('navArr', navArr)
      }
    }
  },

  /**
   * 退出登陆
   * @param state
   * @param commit
   * @param data
   */
  loginOut({ state, commit }, data) {
    commit('routingStack', [])
    commit('routePosition', {})
    commit('navArr', [])
    // commit('menus', [])
    commit('menusList', [])
    commit('menuDefaultActive', {})
    commit('menusDefaultOpeneds', [])
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
